package com.ht.common.core.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.ht.common.core.utils.StringUtils;

/**
 * 判断字段值是否在给定范围内
 * @author zmx
 *
 */
public class StrLenValidator implements ConstraintValidator<StrLenRange, String>{
	// 全局变量存放值集合
	private int selfMinLen =0;
	private int selfFixedLen =0;
	private int selfMaxLen =Integer.MAX_VALUE;
	private boolean required =false;
	/**
	 * 匹配空白字符串
	 */
	private boolean blankMatch;

	 @Override
	    public void initialize(StrLenRange constraintAnnotation) {
			// 获取注解中的值
			 selfMinLen = constraintAnnotation.minLen();
			 selfFixedLen = constraintAnnotation.fixedLen();
			 selfMaxLen = constraintAnnotation.maxLen();
			 required=constraintAnnotation.required();
	    }
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if(required){
			if(StringUtils.isBlank(value)){
				return false;
			}
			return valueValid(value);
		}else{
			if(StringUtils.isBlank(value)){
				return true;
			}
			return valueValid(value);
		}
	}

	private boolean valueValid(String value) {
		int valLen=value.length();
		if(selfFixedLen>0){
			if(valLen==selfFixedLen){
				return true;
			}
		}else{
			if(valLen>=selfMinLen&&valLen<=selfMaxLen){
				return true;
			}
		}
		return false;
	}

}
